let recordert
let videoUrl
let srcObject

async function record() {
    console.log('eeee===> ')
    // 开始录屏
    let captureStream

    try {
        captureStream = await navigator.mediaDevices.getDisplayMedia({
            video: true,
            // audio: true,   not support
            cursor: 'always'
        })
    } catch (e) {
        // 取消录屏或者报错
        alert("Could not get stream")
        return
    }

    srcObject = captureStream
    console.log('captureStream ====> ', captureStream)
    sendMessage({
        srcObject
    })

    // new 一个媒体记录
    recordert = new MediaRecorder(captureStream)
    recordert.start()

    captureStream.getVideoTracks()[0].onended = () => {
        // 录屏结束完成
        recordert.stop()
    }

    recordert.addEventListener("dataavailable", event => {
        // 录屏结束，并且数据可用
        console.log("dataavailable------------")
        videoUrl = URL.createObjectURL(event.data, {
            type: 'video/mp4'
        })
    })
}

function downloads() {
    if (videoUrl) {
        // 下载
        const name = new Date().toISOString().slice(0, 19).replace('T', ' ').replace(" ", "_").replace(/:/g, "-")
        const a = document.createElement('a')
        a.style = 'display: none'
        a.download = `${name}.mp4`
        a.href = videoUrl
        document.body.appendChild(a)
        a.click()
    }
}

function stops() {
    let tracks = srcObject.getTracks()
    tracks.forEach(track => track.stop())
    recordert.stop()
}